#include <bits/stdc++.h>
// 垃圾的一笔的算法
using namespace std;

int n;
vector<int> a;
vector<vector<int>> sons;
unordered_map<long long, long long> memo;
vector<long long> dp;
long long calCost(int x, int y)
{
    if (x == 0 || y == 0)
        return 0;
    return abs(a[x] - a[y]);
}

pair<long long, long long> dfs(int curr, int mNext = 0)
{
    auto &cSons = sons[curr];
    if (cSons.size() == 0)
    {
        dp[curr] = 0;
        return {curr, 0 + calCost(curr, mNext)};
    }
    else if (cSons.size() == 1)
    {
        int u = cSons[0];
        auto p = dfs(u, mNext);
        long long cuCost = calCost(curr, u);
        dp[curr] = cuCost + dp[u];
        return {p.first, cuCost + p.second};
    }
    else if (cSons.size() == 2)
    {
        int u = cSons[0], v = cSons[1];
        // u->v
        auto pU = dfs(u, v), pV = dfs(v, mNext);
        int ux = pU.first;
        long long min_u_to_v = pU.second;
        int vx = pV.first;
        long long min_v_to_next = pV.second;

        long long cost_u_first = calCost(curr, u) + min_u_to_v + min_v_to_next;

        long long dpC1 = calCost(curr, u) + min_u_to_v + dp[v];

        // v->u

        pV = dfs(v, u), pU = dfs(u, mNext);

        vx = pV.first;
        long long min_v_to_u = pV.second;
        ux = pU.first;
        long long min_u_to_next = pU.second;
        long long cost_v_first = calCost(curr, v) + min_v_to_u + min_u_to_next;
        long long dpC2 = calCost(curr, v) + min_v_to_u + dp[u];

        dp[curr] = min(dpC1, dpC2);

        int curX = cost_u_first < cost_v_first ? vx : ux;

        return {curX, min(cost_v_first, cost_u_first)};
    }
    else
    {
        assert(false);
    }
}

int main()
{
    cin >> n;
    a.resize(n + 1);
    sons.resize(n + 1);
    dp.resize(n + 1);
    for (int i = 1; i <= n; ++i)
    {
        int x;
        cin >> x;
        a[i] = x;
    }
    for (int i = 2; i <= n; ++i)
    {
        int f;
        cin >> f;
        sons[f].push_back(i);
    }
    dfs(1);
    cout << dp[1] << endl;
    // system("pause");
    return 0;
}
